from odoo import api, models, fields, _
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_compare


class WorkorderDoneLineQty(models.TransientModel):
    _inherit = 'workorder.done.line.qty'

    def done_move_qty(self):
        # 对外包采购 接收数量进行判断，工序总过数数量，不能超过采购总接收数量
        wo = self.workorder_id
        if wo.is_subcontracting:
            # 采购接收数量
            sub_received_qty = wo.subcontracting_received_qty
            # 本次生产数量
            tot_done = self.qty_produced + self.qty_reject
            # 原始生产数量
            # qty_production = wo.qty_production
            # 以前部分过数数量
            # prev_times_done = wo.qty_op_produced + wo.qty_op_reject
            prep_wos = self.env['mrp.workorder'].search([
                ('production_id', '=', wo.production_id.id),
                ('step', '<', wo.step)
            ])
            # 取前工序报废的数量
            tot_rejects = 0
            for pwo in prep_wos:
                tot_rejects += pwo.qty_op_reject
            # 外包采购接收数量-报废-本次生产数
            end_qty = round(sub_received_qty, 2) - round(tot_done, 2)
            if end_qty < 0:
                # 外包采购数量不足 请先发起采购后
                raise ValidationError(_('If the quantity of outsourcing procurement is insufficient, please initiate the purchase first.'.format(sub_received_qty)))
            if not wo.pol_id.filtered(lambda x: x.state in ['purchase', 'done']) and not wo.pol_ids.filtered(lambda x: x.state in ['purchase', 'done']):
                raise ValidationError(_('Please contact the procurement personnel to confirm the outgoing purchase order.'))
        return super().done_move_qty()
